<?php
namespace app\channel\controller\api;
use app\channel\ApiController;
use think\facade\Cache;

use app\channel\model\ProxyLevelModel;
use app\channel\model\ProxyUsersModel;
use app\member\model\UsersModel;


/*------------------------------------------------------ */
//-- 会员登陆、注册、找回密码相关API
/*------------------------------------------------------ */
class Passport extends ApiController{

    /**
     * 后台初始化
     */
    public function initialize()
    {
        parent::initialize(false);
    }
    /*------------------------------------------------------ */
    //-- 用户登陆
    /*------------------------------------------------------ */
    public function login()
    {
        $this->checkPostLimit('login');//验证请求次数
        $mobile = input('mobile','','trim');
        if(empty($mobile)){
            return $this->error('请填写手机号码.');
        }
        if (checkMobile($mobile) == false){
            return $this->error('登录手机号码格式不正确.');
        }
        $loginErrorNumKey = 'loginErrorNum_'.$mobile;
        $loginError = Cache::get($loginErrorNumKey);
        $data['showVerify'] = false;
        if (empty($loginError)){
            $loginError['num'] = 0;
        }elseif($loginError['num'] > 3){
            $data['showVerify'] = true;
        }
        if ($data['showVerify'] == true){
            $verifyCode = input('verifyCode','','trim');
            $captcha = new \lib\Captcha();
            if(!$captcha->check($verifyCode,request()->header('appsessionid')))
            {
                return $this->error(['图形验证码错误.',-1],'',$data);
            }
        }
        $time = time();
        if ($loginError['num'] >= 10 && $loginError['limitTime'] > $time){//限制不能登陆
            $limitTime = lastLimitTime($loginError['limitTime']);
            return $this->error('登录错误次数过多，请'.$limitTime.'后再操作','',$data);
        }
        $login_type = input('login_type',0,'intval');
        $password = input('password','','trim');
        $code = input('code',0,'intval');
        if ($login_type == 1){
            if (empty($code)){
                return $this->error('请填写短信验证码.');
            }
            $res = $this->checkCode('channel_sms_login',$mobile,$code);//验证短信验证
            if ($res !== true){
                $loginError['num']++;
                $loginError['limitTime'] = $time + 600;
                Cache::set($loginErrorNumKey,$loginError,600);
                return $this->error([$res,-1],'',$data);
            }
        }elseif(empty($password)){
            return $this->error('请填写登录密码.','',$data);
        }
        $UsersModel = new UsersModel();
        $userInfo = $UsersModel->where('mobile',$mobile)->field('user_id,is_channel,password')->find();
        if (empty($userInfo)){
            return $this->error('用户不存在.');
        }

        if($login_type == 0){
            $password = f_hash($password);
            if ($password != $userInfo['password']){
                $loginError['num']++;
                $loginError['limitTime'] = $time + 600;
                Cache::set($loginErrorNumKey,$loginError,600);
                return $this->error(['登录密码不正确.',-1],'',$data);
            }
        }
        if ($userInfo['is_channel'] == 0){
            return $this->error('非代理帐号无法登陆，请核实.','',$data);
        }
        Cache::rm($loginErrorNumKey);
        $ProxyUsersModel = new ProxyUsersModel();
        $proxyUsers = $ProxyUsersModel->info($userInfo['user_id']);
        if ($proxyUsers['status'] == 9){
            return $this->error('帐号被冻结，请联系平台.');
        }

        $upArr['login_time'] = time();
        $upArr['login_ip'] = request()->ip();
        $ProxyUsersModel->where('user_id',$userInfo['user_id'])->update($upArr);
        $data['token'] = $UsersModel->doLogin($userInfo['user_id'],input('source'),'channel');

        return $this->success($data);
    }
	/*------------------------------------------------------ */
	//-- 查询邀请者信息
	/*------------------------------------------------------ */
 	public function searchShareUser(){
        $UsersModel = new UsersModel();
        $share_token = input('share_token','','trim');
        $invite_proxy_id = input('proxy_id',0,'intval');
        $is_factory = false;
        if (empty($share_token) == false){
            if ($share_token == settings('channel_token')){
                $is_factory = true;//平台邀请码
            }
            $where[] = ['token','=',$share_token];
        }else{
            $verifyCode = input('verifyCode','','trim');
            $captcha = new \lib\Captcha();
            if(!$captcha->check($verifyCode,request()->header('appsessionid')))
            {
                return $this->error('图形验证码错误.');
            }
            $shareMobile = input('shareMobile') * 1;
            if (empty($shareMobile)){
                return $this->error('请输入邀请人手机号码.');
            }
            $where[] = ['mobile','=',$shareMobile];
        }

        $ProxyLevelModel = new ProxyLevelModel();
        if ($is_factory == true){
            $data['proxy_name'] = '厂家';
            $data['real_name'] = settings('channel_real_name');
            $data['mobile'] = mobileSubstr(settings('channel_mobile'));
            $data['proxyInvitelist'] = $ProxyLevelModel->getInvitelist(0,$invite_proxy_id);
            if (empty($data['proxyInvitelist'])){
                return $this->error(['当前邀请链接已失效.',-1]);
            }
            $data['share_token'] = settings('channel_token');
        }else{
            $userInfo = $UsersModel->where($where)->field('user_id,real_name,mobile,is_channel,token')->find();
            if (empty($userInfo) == true || $userInfo['is_channel'] == 0){
                return $this->error('没有找到相关代理信息.');
            }
            $proxyUserInfo = (new ProxyUsersModel)->info($userInfo['user_id'],'user_id');
            if (empty($proxyUserInfo) == true){
                return $this->error('没有找到相关代理信息.');
            }
            if ($proxyUserInfo['status'] != 1){
                return $this->error(['当前代理无法邀请，请联系相关代理.',-1]);
            }
            $data['proxyInvitelist'] = $ProxyLevelModel->getInvitelist($proxyUserInfo['proxy_id'],$invite_proxy_id);
            if (empty($data['proxyInvitelist'])){
                return $this->error(['当前邀请链接已失效.',-1]);
            }
            $data['proxy_name'] = $ProxyLevelModel->info($proxyUserInfo['proxy_id'],true);
            $data['real_name'] = $userInfo['real_name'];
            $data['mobile'] = mobileSubstr($userInfo['mobile']);
            $data['share_token'] = $userInfo['token'];
        }

        return $this->success($data);
	}
    /*------------------------------------------------------ */
    //-- 验证注册手机
    /*------------------------------------------------------ */
    public function checkMobile(){
        $type = input('type','','trim');
        $mobile = input('mobile','','trim');
        $code = input('code','','intval');
        if (empty($mobile)){
            return $this->error('请输入手机号码.');
        }
        $res = $this->checkCode($type,$mobile,$code);//验证短信验证
        if ($res !== true){
            return $this->error($res);
        }
        $userInfo = (new UsersModel)->where('mobile',$mobile)->field('user_id,is_channel,real_name,password')->find();
        $data['user_exist'] = 0;
        $data['set_password'] = 1;
        $data['real_name'] = '';

        if (empty($userInfo) == false){
           $count = (new ProxyUsersModel)->where('user_id',$userInfo['user_id'])->count();
           if ($count > 0){
               return $this->error('当前手机号码已注册代理.');
           }
           $data['user_exist'] = 1;
           $data['real_name'] = $userInfo['real_name'];
           if (empty($userInfo['password']) == false){//已存在密码不需要输入密码
               $data['set_password'] = 0;
           }
        }
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 注册﻿
    /*------------------------------------------------------ */
    public function register(){
        $mobile = input('mobile','','trim');
        if (empty($mobile)){
            return $this->error('请填写注册手机号码.');
        }
        if (checkMobile($mobile) == false){
            return $this->error('注册手机号码格式不正确.');
        }
        $share_token = input('share_token','','trim');
        if (empty($share_token)){
            return $this->error('没有邀请上级不能注册.');
        }
        $real_name = input('real_name',0,'trim');
        if (empty($real_name)){
            return $this->error('真实姓名不能为空.');
        }
        $signature = input('signature');
        if (empty($signature)){
            return $this->error('请签署代理协议后再操作.');
        }
        $proxy_id = input('proxy_id',0,'intval');
        if ($proxy_id < 1){
            return $this->error('请选择需申请的代理层级.');
        }
        $password = input('password','','trim');
        $UsersModel = new UsersModel();
        $userInfo = $UsersModel->where('mobile',$mobile)->field('user_id,is_channel,password')->find();
        if (empty($userInfo) == true){
            if (empty($password) == true){
                return $this->error('请填写用户密码.');
            }
            $inArr['user_id'] = 0;
            $inArr['password'] = $password;
        }else{
            if ($userInfo['is_channel'] == 1){
                return $this->error('当前手机号码已注册代理.');
            }
            if (empty($userInfo['password']) == true && empty($password) == true){
                return $this->error('请填写用户密码.');
            }
            $inArr['user_id'] = $userInfo['user_id'];
        }
        $ProxyUsersModel = new ProxyUsersModel();
        $ProxyLevelModel = new ProxyLevelModel();
        $proxyLevelList = $ProxyLevelModel->getlist();//获取全部层级
        if ($proxyLevelList[$proxy_id]['is_invite'] == 0){
            return $this->error('不能申请成为'.$proxyLevelList[$proxy_id]['proxy_name'].'.');
        }

        if ($share_token == settings('channel_token')){
            $inArr['pid'] = 0;
            $inArr['purchase_pid'] = 0;
        }else{
            $shareInfo = $UsersModel->where('token',$share_token)->field('user_id,is_channel')->find();
            if ($shareInfo['is_channel'] == 0){
                return $this->error('没有找到相关代理信息.');
            }
            $proxyUserInfo = $ProxyUsersModel->info($shareInfo['user_id']);
            if (empty($proxyUserInfo) == true){
                return $this->error('没有找到相关代理信息.');
            }
            $proxyInvitelist = $ProxyLevelModel->getInvitelist($proxyUserInfo['proxy_id']);//获取可邀请层级
            if (empty($proxyInvitelist)){
                return $this->error('相关代理暂无权邀请.');
            }
            $proxyIds = [];
            foreach ($proxyInvitelist as $pl){
                $proxyIds[] = $pl['value'];
            }
            if (in_array($proxy_id,$proxyIds) == false){
                return $this->error('不能申请成为'.$proxyLevelList[$proxy_id]['proxy_name'].'.');
            }
            $inArr['pid'] = $shareInfo['user_id'];
            $inArr['supply_uid'] = $ProxyUsersModel->getPurchaseUid($proxy_id,$inArr['pid'],$proxyLevelList);
            if ($proxyUserInfo['proxy_id'] == $proxy_id){
                $inArr['is_regress'] = 1;//设置可以回归
            }

        }
        $inArr['proxy_id'] = $proxy_id;
        $proxyLevel = $proxyLevelList[$proxy_id];
        if ($proxyLevel['is_join_limit'] == 0){//不限制加入门槛
            $inArr['join_condition'] = 1;
        }
        if ($proxyLevel['is_auto'] == 1){//自动审核
            $inArr['status'] = 1;
        }
        $inArr['real_name'] = $real_name;
        $extend = getFileExtend($signature);
        if ($extend == false){
            return $this->error('未能识别签名图片，请尝试重新上传.');
        }
        $file_path = config('config._upload_') . 'signature/';
        $file_name = random_str(15).rand(10,99).'.'.$extend[1];
        $res = base64ToImage($signature,$file_path,$file_name);
        if ($res == false){
            return $this->error('签名保存失败，请重试.');
        }
        $inArr['signature'] = trim($file_path.$file_name, '.');
        $inArr['mobile'] = $mobile;
        $res = $ProxyUsersModel->register($inArr,$this);
        if ($res !== true){
            return $this->error($res);
        }
        return $this->success();
    }
    /*------------------------------------------------------ */
    //-- 找回密码
    /*------------------------------------------------------ */
    public function forget(){

        $mobile = input('mobile','','trim');
        $code = input('code','','intval');
        if (empty($mobile)){
            return $this->error('请输入手机号码.');
        }
        $password = input('password','','trim');
        if (empty($password)){
            return $this->error('请输入新的密码.');
        }

        $forgetErrorNumKey = 'forgetErrorNum_'.$mobile;
        $forgetError = Cache::get($forgetErrorNumKey);
        $data['showVerify'] = false;
        if (empty($forgetError)){
            $forgetError['num'] = 0;
        }elseif($forgetError['num'] > 3){
            $data['showVerify'] = true;
        }
        if ($data['showVerify'] == true){
            $verifyCode = input('verifyCode','','trim');
            $captcha = new \lib\Captcha();
            if(!$captcha->check($verifyCode,request()->header('appsessionid')))
            {
                return $this->error(['图形验证码错误.',-1],'',$data);
            }
        }
        $time = time();
        if ($forgetError['num'] >= 10 && $forgetError['limitTime'] > $time){//限制不能登陆
            $limitTime = lastLimitTime($forgetError['limitTime']);
            return $this->error('错误次数过多，请'.$limitTime.'后再操作','',$data);
        }

        $res = $this->checkCode('channel_sms_forget_pw',$mobile,$code);//验证短信验证
        if ($res !== true){
            $forgetError['num']++;
            $forgetError['limitTime'] = $time + 3600;
            Cache::set($forgetErrorNumKey,$forgetError,3600);
            return $this->error([$res,-1],'',$data);
        }
        $UsersModel = new UsersModel();
        $user_id = $UsersModel->where('mobile',$mobile)->value('user_id');
        if (empty($user_id) == true){
            return $this->error('没有找到当前手机注册的帐号');
        }
        $data['mobile'] = $mobile;
        $data['password'] = $password;
        $res = $UsersModel->forgetPwd($data,$this);
        if ($res !== true){
            return $this->error($res);
        }
        Cache::rm($forgetErrorNumKey);
        return $this->success();
    }
}
